import { View, Text, SwiperItem, Swiper, Image } from "@tarojs/components";
import { useLoad } from "@tarojs/taro";
import "./index.scss";
import { useEffect, useMemo, useState } from "react";
import { TabComp } from "@/components/Tab";
import b1 from "../../../assets/banners/b1.png";
import b2 from "../../../assets/banners/b2.png";
import { adsReq } from "@/common/api";

import dayjs from "dayjs";

import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@/store";
import Taro from "@tarojs/taro";
import tools from "@/common/tools";

const FLIGHT_TABS = [
  {
    label: "单程",
    id: 0,
  },
  {
    label: "多程",
    id: 1,
  },
  {
    label: "往返",
    id: 2,
  },
];

const ADVS_BANNER = [
  {
    imgUrl: b1,
    linkUrl: "https://www.taobao.com",
  },
  {
    imgUrl: b2,
    linkUrl: "https://www.taobao.com",
  },
];

export const FlightIndex = () => {
  useLoad(() => {
    console.log("Page loaded.");
  });

  // const [tabIndex, setTabIndex] = useState(0);

  const { arrCityName, dptCityName, dptDate } = useSelector(
    (state: RootState) => state.flightIndex
  );
  // console.log("flightState", flightState);

  const dispatch = useDispatch();

  const chooseFlightCity = (type: "depart" | "arrive") => {
    dispatch({
      type: "flightIndex/updateState",
      payload: {
        cityType: type,
      },
    });
    // 注意：使用app.config.js中注册的绝对路径，需要加/
    Taro.navigateTo({
      // url: "/pages/airportList/airportList"
      url: "/pages/airportList/index",
    });
  };

  const chooseFlightDate = () => {
    // dispatch({
    //   type: "flightIndex/updateState",
    //   payload: {
    //     dateType: "date",
    //   },
    // });
    // 注意：使用app.config.js中注册的绝对路径，需要加/
    Taro.navigateTo({
      // url: "/pages/airportList/airportList"
      url: "/pages/calendar/index",
    });
  };

  const getCityInfo = async ({
    latitude,
    longitude,
  }: {
    latitude: number;
    longitude: number;
  }) => {
    try {
      const res = await Taro.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?key=DGZBZ-IVYCQ-7HN54-GJG3F-W5VE7-IXFEA&location=${latitude},${longitude}`,
      });

      console.log("cityInfo: ", res);
      const cityInfo = res?.data?.result?.ad_info || {};
      console.log("cityInfo: ", cityInfo);
      dispatch({
        type: "flightIndex/updateState",
        payload: {
          deptCityId: cityInfo?.city_code || 2,
          deptCityName: cityInfo?.city || "上海",
        },
      });
    } catch (error) {
      tools.showToast({
        title: "获取城市失败",
        icon: "none",
        duration: 2000,
      });
    }
  };

  const getLocationInfo = async () => {
    try {
      const res = await Taro.getLocation({
        type: "gcj02",
      });
      console.log("locationInfo: ", res);

      getCityInfo(res);
    } catch (error) {
      console.log("获取位置失败: ", error);

      tools.showToast({
        title: "获取位置失败",
        icon: "none",
        duration: 2000,
      });
    }
  };

  const [adList, setAdList] = useState(ADVS_BANNER);

  const getAds = async () => {
    const res: any = await adsReq({});
    console.log("res: ", res);
    if (res.code === 1) {
      setAdList(res.result);
    }
  };

  const handleTabClick = (id: number) => {
    console.log(id);
  };

  useEffect(() => {
    getAds();
    getLocationInfo();
  }, []);

  return (
    <View className="flight-container">
      <View className="flight-top">
        <TabComp
          tabList={FLIGHT_TABS}
          onTabClick={handleTabClick}
          className="flight-index-tab"
        >
          <SwiperItem>
            <View className="item station">
              <View className={`cell from `}>{dptCityName}</View>
              <Text className={`icon-zhihuan iconfont `}></Text>
              <View className={`cell to `}>{arrCityName}</View>
            </View>

            {/* <Button className="search-btn" onClick={this.onLinkToList}>
              搜一下吧～
            </Button> */}
          </SwiperItem>
          <SwiperItem>
            {/* <View className="item station">
              <View
                className={`cell from ${isExchange ? "slide" : ""}`}
                onClick={() => chooseFlightCity("depart")}
              >
                {dptCityName}
              </View>
              <Text
                onClick={this.exchangeCity}
                className={`icon-zhihuan iconfont ${
                  isExchange ? "active" : ""
                }`}
              ></Text>
              <View
                className={`cell to ${isExchange ? "slide" : ""}`}
                onClick={() => chooseFlightCity("arrive")}
              >
                {arrCityName}
              </View>
            </View>
            <View className="item date" onClick={this.chooseFlightDate}>
              {dayjs(dptDate).format("M月D日")}
            </View>
            <Button className="search-btn" onClick={this.onLinkToList}>
              搜一下吧～
            </Button> */}
          </SwiperItem>
          {/*  往返  */}
          {/* <SwiperItem>
              <NoExploit className="no-data" />
            </SwiperItem> */}
          {/*  多程  */}
          {/* <SwiperItem>
              <NoExploit className="no-data" />
            </SwiperItem> */}
        </TabComp>
      </View>

      <Swiper className="advs-banner-bd" autoplay interval={3000} circular>
        {adList.map((item, index) => (
          <SwiperItem key={index} className="item">
            <Image
              src={item.imgUrl}
              onClick={() => window.open(item.linkUrl)}
              className="img"
            ></Image>
          </SwiperItem>
        ))}
      </Swiper>
    </View>
  );
};
